//
//  SearchHistorView.m
//  MedicalCare
//
//  Created by lbh on 2021/10/11.
//  Copyright © 2021 hs. All rights reserved.
//

#import "SearchHistorView.h"

@implementation SearchHistorView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self makeUI];
    }
    return self;
}

#pragma maek --Private
- (void)makeUI {
    // 搜索记录
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.bgView];
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
    if ([FKCacheTool isOpenSearchRecord]) {
        [self.bgView addSubview:self.topBgView];
        [self.topBgView addSubview:self.hostLabel];
        [self.topBgView addSubview:self.deleteBtn];
        [self.bgView addSubview:self.sktagBgView];
        
        [self.topBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(46);
        }];
        [self.hostLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.topBgView.mas_centerY);
            make.left.mas_equalTo(12);
        }];
        [self.deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.topBgView.mas_centerY);
            make.right.mas_equalTo(-12);
            make.width.mas_equalTo(24);
            make.height.mas_equalTo(24);
        }];
        [self.sktagBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.topBgView.mas_bottom).offset(0);
            make.right.mas_equalTo(-12);
            make.left.mas_equalTo(12);
            make.height.mas_equalTo(100);
        }];
        
        //热门搜索
        [self.bgView addSubview:self.hottopBgView];
        [self.hottopBgView addSubview:self.hothostLabel];
        [self.bgView addSubview:self.hotsktagBgView];
        
        [self.hottopBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.sktagBgView.mas_bottom).offset(20);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(46);
        }];
        [self.hothostLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.hottopBgView.mas_centerY);
            make.left.mas_equalTo(12);
        }];
        [self.hotsktagBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.hottopBgView.mas_bottom).offset(0);
            make.right.mas_equalTo(-12);
            make.left.mas_equalTo(12);
            make.height.mas_equalTo(1000);
        }];
        
        // 加载历史搜索记录
        [self showSearchHistory];
        [self isShowDelete];
        [self isShowLabel];
    } else {
        [self.bgView addSubview:self.hottopBgView];
        [self.hottopBgView addSubview:self.hothostLabel];
        [self.bgView addSubview:self.hotsktagBgView];
        
        [self.hottopBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(0);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.height.mas_equalTo(46);
        }];
        [self.hothostLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(self.hottopBgView.mas_centerY);
            make.left.mas_equalTo(12);
        }];
        [self.hotsktagBgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.hottopBgView.mas_bottom).offset(0);
            make.right.mas_equalTo(-12);
            make.left.mas_equalTo(12);
            make.height.mas_equalTo(1000);
        }];
    }
}
- (void)showSearchHistory{
    self.hidden = NO;
    [self setUpSktagView];
}
- (void)disMissSearchHistory{
    self.hidden = YES;
}
- (void)addHistory:(NSString *)history{
    NSString *histotyStr = [self homeSearchValue];
    NSArray *historyArray = [histotyStr componentsSeparatedByString:@","];
    NSMutableArray *historyMut = [[NSMutableArray alloc]init];
    if (historyArray.count == 0) {
        [historyMut addObject:history];
        NSString *newHistory = [historyMut componentsJoinedByString:@","];
        [CacheManager archiveObj:newHistory namePath:[self homeSearchPath]];
    }
    else{
        if (![historyArray containsObject:history]) {
            [historyMut addObject:history];
            [historyMut addObjectsFromArray:historyArray];
            NSString *newHistory = [historyMut componentsJoinedByString:@","];
            [CacheManager archiveObj:newHistory namePath:[self homeSearchPath]];
        }
    }
    [self screenHistoreWords];
    [self isShowDelete];
    [self isShowLabel];
    [self setUpSktagView];
}
//对历史数据进行筛选
- (void)screenHistoreWords{
    NSInteger total = 10;
    NSString *histotyStr = [self homeSearchValue];
    NSArray *historyArray = [histotyStr componentsSeparatedByString:@","];
    NSMutableArray *historyMut = [[NSMutableArray alloc]init];
    if (historyArray.count > total) {
        for (NSInteger i = 0; i < 10; i++) {
            NSString *hisStr = historyArray[i];
            [historyMut addObject:hisStr];
        }
        NSString *newHistory = [historyMut componentsJoinedByString:@","];
        [CacheManager archiveObj:newHistory namePath:[self homeSearchPath]];
    }
}
- (NSString *)homeSearchValue{
    return  [CacheManager unarchiveObj:[self homeSearchPath]];
}
- (void)isShowDelete{
    NSString *histotyStr = [self homeSearchValue];
    if ([NSString isEmpty:histotyStr]) {
        self.deleteBtn.hidden = YES;
    }
    else{
        self.deleteBtn.hidden = NO;
    }
}
- (void)isShowLabel{
    NSString *histotyStr = [self homeSearchValue];
    if ([NSString isEmpty:histotyStr]) {
        self.hostLabel.hidden = YES;
    }
    else{
        self.hostLabel.hidden = NO;
    }
}
- (BOOL)isHasHistory{
    NSString *histotyStr = [self homeSearchValue];
    NSArray *historyArray = [histotyStr componentsSeparatedByString:@","];
    if (historyArray.count == 0) {
        return NO;
    }
    else{
        return YES;
    }
}
//历史搜索
- (void)setUpSktagView{
    NSString *histotyStr = [self homeSearchValue];
    NSArray *historyArray = [histotyStr componentsSeparatedByString:@","];
    [self.sktagBgView removeAllTags];
    // 这东西非常关键
    self.sktagBgView.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 24;
    self.sktagBgView.padding = UIEdgeInsetsMake(5, 0, 5, 0);
    self.sktagBgView.lineSpacing = 15;
    self.sktagBgView.interitemSpacing = 15;
    
    WeakSelf(weakSelf);
    [historyArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SKTag *tag = [[SKTag alloc] initWithText:obj];
        tag.font = [UIFont systemFontOfSize:17];
        tag.padding = UIEdgeInsetsMake(6, 20, 6, 20);
        tag.cornerRadius = 16;
        //选择颜色按钮的字体颜色
        tag.textColor = RBG(93, 91, 94);
        tag.bgColor = [UIColor colorWithHex:@"#F6F7F9"];
        tag.borderColor = [UIColor blackColor];
        tag.borderWidth = 0;
        [weakSelf.sktagBgView addTag:tag];
        
    }];
    WeakSelf(weakSlf)
    self.sktagBgView.didTapTagAtIndex = ^(NSUInteger index) {
        [[KFTools getCurrentVC].view endEditing:YES];
        NSString *histotyStr = [weakSlf homeSearchValue];
        NSArray *historyArray = [histotyStr componentsSeparatedByString:@","];
        !weakSlf.historyViewTagBlock?:weakSlf.historyViewTagBlock(historyArray[index]);
    };
    CGFloat tagHeight = self.sktagBgView.intrinsicContentSize.height;
    [self.sktagBgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(tagHeight);
    }];
    
    if (historyArray.count == 0) {
        [self.topBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(0);
        }];
        [self.hottopBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.sktagBgView.mas_bottom).offset(0);
        }];
    }
    else{
        [self.topBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(46);
        }];
        [self.hottopBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.sktagBgView.mas_bottom).offset(20);
        }];
    }
//    self.topBgView.backgroundColor =UIColor.redColor;
//    self.sktagBgView.backgroundColor  = UIColor.greenColor;
//    
//    self.hottopBgView.backgroundColor =UIColor.purpleColor;
//    self.hotsktagBgView.backgroundColor  = UIColor.blueColor;
}
#pragma mark - Privateley Methods
//首页搜索路径
- (NSString *)homeSearchPath {
    return [NSString stringWithFormat:@"%@%@",@"HomeSearch",self.searchType];
}

#pragma mark --Action
- (void)deleteBtnAction:(UIButton *)btn {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"您确定要删除搜索历史么?" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *certainAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [CacheManager removeObj:[self homeSearchPath]];
        [self isShowDelete];
        [self isShowLabel];
        [self setUpSktagView];
    }];
    [alertController addAction:cancelAction];
    [alertController addAction:certainAction];
    [[KFTools getCurrentVC] presentViewController:alertController animated:YES completion:nil];
}

#pragma mark --搜索热词
- (void)setHotArray:(NSArray *)hotArray{
    hotArray = [[hotArray reverseObjectEnumerator] allObjects];
    _hotArray = hotArray;
    [self setUpHotSktagView];
}
//搜索热词
- (void)setUpHotSktagView{
    NSArray *historyArray = self.hotArray;
    [self.hotsktagBgView removeAllTags];
    // 这东西非常关键
    self.hotsktagBgView.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width - 24;
    self.hotsktagBgView.padding = UIEdgeInsetsMake(5, 0, 5, 0);
    self.hotsktagBgView.lineSpacing = 15;
    self.hotsktagBgView.interitemSpacing = 15;
    
    WeakSelf(weakSelf);
    [historyArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SKTag *tag = [[SKTag alloc] initWithText:obj];
        tag.font = [UIFont systemFontOfSize:17];
        tag.padding = UIEdgeInsetsMake(6, 20, 6, 20);
        tag.cornerRadius = 16;
        //选择颜色按钮的字体颜色
        tag.textColor = RBG(93, 91, 94);
        tag.bgColor = [UIColor colorWithHex:@"#F6F7F9"];
        tag.borderColor = [UIColor blackColor];
        tag.borderWidth = 0;
        [weakSelf.hotsktagBgView addTag:tag];
        
    }];
    WeakSelf(weakSlf)
    self.hotsktagBgView.didTapTagAtIndex = ^(NSUInteger index) {
        [[KFTools getCurrentVC].view endEditing:YES];
        NSArray *historyArray = weakSlf.hotArray;
        !weakSlf.hotViewTagBlock?:weakSlf.hotViewTagBlock(historyArray[index]);
    };
    CGFloat tagHeight = self.hotsktagBgView.intrinsicContentSize.height;
    [self.hotsktagBgView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(tagHeight);
    }];
}
#pragma mark --Lazy
- (UIView *)bgView {
    
    if (!_bgView) {
        _bgView = [[UIView alloc]init];
        _bgView.backgroundColor = UIColor.whiteColor;
    }
    return _bgView;
}
- (UIView *)topBgView {
    
    if (!_topBgView) {
        _topBgView = [[UIView alloc]init];
        _topBgView.backgroundColor = [UIColor whiteColor];
    }
    return _topBgView;
}
- (UILabel *)hostLabel {
    if (!_hostLabel) {
        _hostLabel = [[UILabel alloc]init];
        _hostLabel.text = @"搜索记录";
        _hostLabel.textColor = [UIColor colorWithHex:@"#333333"];
        _hostLabel.font = kBoldFont(18);
    }
    return _hostLabel;
}
- (UIButton *)deleteBtn {
    if (!_deleteBtn) {
        _deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_deleteBtn setImage:[UIImage imageNamed:@"icon_search_delete"] forState:UIControlStateNormal];
        [_deleteBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_deleteBtn addTarget:self action:@selector(deleteBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _deleteBtn;
}
- (SKTagView *)sktagBgView {
    
    if (!_sktagBgView) {
        _sktagBgView = [[SKTagView alloc]init];
        _sktagBgView.backgroundColor = [UIColor whiteColor];
    }
    return _sktagBgView;
}
//热门搜索
- (UIView *)hottopBgView {
    
    if (!_hottopBgView) {
        _hottopBgView = [[UIView alloc]init];
        _hottopBgView.backgroundColor = [UIColor whiteColor];
    }
    return _hottopBgView;
}
- (UILabel *)hothostLabel {
    if (!_hothostLabel) {
        _hothostLabel = [[UILabel alloc]init];
        _hothostLabel.text = @"热门搜索";
        _hothostLabel.textColor = [UIColor colorWithHex:@"#333333"];
        _hothostLabel.font = kBoldFont(18);
    }
    return _hothostLabel;
}
- (SKTagView *)hotsktagBgView {
    
    if (!_hotsktagBgView) {
        _hotsktagBgView = [[SKTagView alloc]init];
        _hotsktagBgView.backgroundColor = [UIColor whiteColor];
    }
    return _hotsktagBgView;
}

@end
